﻿using System.Configuration;
using System.Transactions;
using SportTraining.Core.Dal;

namespace SportTraining.Core.Linq2Sql
{
    public partial class SportTrainingDataContext : IDataContext
    {
        private const string connectionStringName = "SportTraining";

        private static string GetConnectionString(bool useAppConfig)
        {
            string resultConnectionString = Properties.Settings.Default.SportTrainingConnectionString;

            if (useAppConfig && ConfigurationManager.ConnectionStrings[connectionStringName] != null)
            {
                resultConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
            }

            return resultConnectionString;
        }

        public SportTrainingDataContext(bool useAppConfig) : base(GetConnectionString(useAppConfig), mappingSource)
        {
            OnCreated();

            bool createDb;
            bool.TryParse(ConfigurationManager.AppSettings["createDb"], out createDb);

            if (!DatabaseExists())
            {
                if (!createDb)
                {
                    string errorMessage =
                        string.Format("Не обнаружена рабочая БД.\nПроверьте правильность строки соединения : {0}",
                                      Connection.ConnectionString);
                    throw new SportTrainigException(errorMessage);
                }

                CreateDatabase();

                FillDb();

            }
        }

        private void FillDb()
        {
            var section1 = new Section {Name = "Секция1"};
            var section2 = new Section {Name = "Секция2"};

            Sections.InsertAllOnSubmit(new []{section1, section2});

            Price priceItemForSection1 = new Price {Cost = 10, Section = section1};
            Price priceItemForSection2 = new Price { Cost = 20, Section = section2 };

            Prices.InsertAllOnSubmit(new []{priceItemForSection1, priceItemForSection2});

            Save();
        }

        #region Implementation of IDataContext

        public void Save()
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                SubmitChanges();
                transaction.Complete();
            }
        }

        #endregion
    }
}